const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

const auth = {
  async signup(parent, args, ctx, info) {
    const password = await bcrypt.hash(args.password, 10)
    // 添加一个默认的 Group
    const user = await ctx.db.mutation.createUser({
      data: {
        ...args,
        password,
        groups: {
          create: [
            {
              name: '已关注'
            }
          ]
        }
      }
    })

    return {
      token: jwt.sign({ userId: user.id }, process.env.APP_SECRET),
      user
    }
  },

  async login(parent, { email, password }, ctx, info) {
    const user = await ctx.db.query.user({ where: { email } })
    if (!user) {
      throw new Error(`No such user found for email: ${email}`)
    }

    const valid = await bcrypt.compare(password, user.password)
    if (!valid) {
      throw new Error('Invalid password')
    }

    return {
      token: jwt.sign({ userId: user.id }, process.env.APP_SECRET),
      user
    }
  },

  async wxLogin(parent, { openid }, ctx, info) {
    const user = await ctx.db.query.users({ where: { phone: openid } })
    console.log(user)
    if (!user || user.length === 0) {
      throw new Error(`No such user found for phone: ${openid}`)
    }

    return {
      token: jwt.sign({ userId: user[0].id }, process.env.APP_SECRET),
      user: user[0]
    }
  }
}

module.exports = { auth }
